package com.springcloud.annotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @author 顾志杰
 * @date 2021/5/31-13:27
 */
@Aspect
@Component
@Slf4j
public class AccessLimiterAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    @Pointcut("@annotation(com.springcloud.annotation.AccessLimiter)")
    public void cut() {
        log.info("cut");
    }

    @Before("cut()")
    public void before(JoinPoint joinPoint) {
        // 1.获得方法签名 作为method Key
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AccessLimiter accessLimiter = method.getAnnotation(AccessLimiter.class);
        if (accessLimiter == null) {
            return;
        }
        String key = accessLimiter.methodKey();
        Integer limit = accessLimiter.limit();
        // 如果没设置methodkey  从方法签名自动生成一个key
        if (StringUtils.isEmpty(key)) {
            Class<?>[] types = method.getParameterTypes();
            key = method.getDeclaringClass().getName()+"."+method.getName();
            if (types != null) {
                String paramTypes = Arrays.stream(types)
                        .map(Class::getName)
                        .collect(Collectors.joining(","));
                log.info("param types: " + paramTypes);
                key += "#" + paramTypes;
            }
        }
        // 2.调用redis
        /*step 1 : request Lua script*/
        boolean acquired = redisTemplate.execute(
                rateLimitLua, // Lua 脚本
                Lists.newArrayList(key), // Lua脚本中的key列表
                limit.toString() //Lua脚本中的value列表
        );
        if (!acquired) {
            log.error("Your access is blocked, key = {}", key);
            throw new RuntimeException("请求不通过");
        }
    }
}
